<template>
  <div>
    <el-button style="margin: 40px 0" type="primary" size="mini" @click="submitForm('formRef')">保存</el-button>

    <el-form :model="tableForm" ref="formRef" class="demo-ruleForm">
      <el-table :data="tableForm.tableData" :header-cell-style="{ 'text-align': 'center' }"
                :cell-style="{ 'text-align': 'center' }">
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column prop="department" label="所属部门" width="200px">
          <template v-slot="scope">
            <el-form-item
                :prop="'tableData.' + scope.$index + '.department'"
                :rules="{ required: true, message: '证件类型不能为空', trigger: 'change'}"
            >
              <el-select size="small" clearable v-model="scope.row.department" filterable placeholder="请选择所属部门">
                <el-option v-for="item in documentTypeList" :key="item.id" :label="item.value"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="200px">
          <template v-slot="scope">
            <el-form-item
                :prop="'tableData.' + scope.$index + '.name'"
                :rules="{ required: true, message: '姓名不能为空', trigger: 'blur'}"
            >
              <el-input size="small" v-model="scope.row.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template #default="{ row, $index }">
            <el-button @click="addFormRow(row)" type="text" size="small">添加</el-button>
            <el-button type="text" size="small" @click="tableForm.tableData.splice($index, 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      documentTypeList: [
        {id: 1, value: '研发'},
        {id: 2, value: '产品'}
      ],
      tableForm: {
        tableData: [
          {department: '', name: ''},
          {department: '', name: ''}
        ]
      }
    };
  },
  mounted() {
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!', this.tableForm);
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addFormRow() {
      this.tableForm.tableData.push({department: '', name: ''});
    }
  }
};
</script>
